"""聊天小程序--单任务版(只能发一次回一次)"""
import socket


def set_receive_info(rece_info):
    # rece_ip = input("请输入待接收方的ip:")
    rece_ip = '192.168.0.109'
    # rece_port = input("请输入待接收的端口号:")
    rece_port = '9011'
    rece_info = (rece_ip, int(rece_port))
    print("接收方主机%s记录成功" % str(rece_info))
    return rece_info


def send_message(udp_socket, rece_info):
    send_data = input("输入发送的数据:")

    udp_socket.sendto(send_data.encode(), rece_info)
    print('发送成功.....')


def receive_message(udp_socket):
    rec_data = udp_socket.recvfrom(1024)
    print('接收到数据,正在解析....', rec_data)
    print("收到消息:%s" % rec_data[0].decode('gbk'))


def main():
    # 创建一个套接字
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # 为这个套接字绑定一个ip和端口号
    udp_socket.bind(("192.168.0.25", 9011))
    rece_info = ''  # 待接收方的主机信息
    while True:
        print("1.发送消息,2.接收消息,3.重置收信人,4.退出")
        num = input("请输入:")
        if num == "1":
            if rece_info == '':
                rece_info = set_receive_info(rece_info)

            send_message(udp_socket, rece_info)
        elif num == '2':
            receive_message(udp_socket)
        elif num == '4':
            break
        elif num == '3':
            rece_info = set_receive_info(rece_info)
        else:
            print('输入无效')

    # 关闭一个套接字
    udp_socket.close()


if __name__ == '__main__':
    main()
